<template>
  <div class="user-container">
    <el-card class="user-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-buttons">
            <el-button type="primary" @click="showAddDialog">添加用户</el-button>
          </div>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :model="queryForm" inline class="query-form">
        <el-form-item label="用户名">
          <el-input v-model="queryForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="queryForm.realName" placeholder="请输入真实姓名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表 -->
      <el-table :data="users" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phoneNumber" label="手机号" width="120" />
        <el-table-column prop="departmentId" label="部门" width="120">
          <template #default="{ row }">
            {{
              departments.find((dept) => dept.id === row.departmentId)?.fullPath ||
              departments.find((dept) => dept.id === row.departmentId)?.name ||
              '-'
            }}
          </template>
        </el-table-column>
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roles" label="角色" width="150">
          <template #default="{ row }">
            <el-tag v-for="role in row.roles" :key="role.id" class="role-tag">
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="showEditDialog(row)">编辑</el-button>
            <el-button type="primary" link @click="showRoleDialog(row)">角色</el-button>
            <el-button type="primary" link @click="showPasswordDialog(row)">修改密码</el-button>
            <el-button type="danger" link @click="handleStatusChange(row)">
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '添加用户'" width="500px">
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.phoneNumber" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="userForm.departmentId"
            placeholder="请选择部门"
            clearable
            class="w-full"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.fullPath || dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="userForm.position" />
        </el-form-item>
        <el-form-item label="密码" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色设置对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="角色设置"
      width="500px"
      @opened="handleDialogOpened"
    >
      <el-tree
        ref="roleTree"
        :data="roles"
        show-checkbox
        node-key="id"
        :props="{ label: 'description' }"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRoleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="新密码" required>
          <el-input
            v-model="passwordForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" required>
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

interface Role {
  id: number
  name: string
}

interface User {
  id: number
  username: string
  realName: string
  email: string
  phoneNumber: string
  departmentId: number
  position: string
  status: number
  roles: Role[]
  createdAt: string
  updatedAt: string
}

interface QueryForm {
  username: string
  realName: string
  status: string
}

interface Department {
  id: number
  name: string
  fullPath?: string
}

const users = ref<User[]>([])
const roles = ref<Role[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const roleDialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const isEdit = ref(false)
const currentUser = ref<User | null>(null)
const roleTree = ref()
const departments = ref<Department[]>([])

const queryForm = reactive<QueryForm>({
  username: '',
  realName: '',
  status: '',
})

const userForm = ref({
  username: '',
  realName: '',
  phoneNumber: '',
  email: '',
  departmentId: undefined as number | undefined,
  position: '',
  password: '',
})

const passwordForm = ref({
  password: '',
  confirmPassword: '',
})

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      username: queryForm.username || undefined,
      realName: queryForm.realName || undefined,
      status: queryForm.status || undefined,
    }

    const response = await axios.get('/api/users', { params })

    if (response.data && response.data.content) {
      users.value = response.data.content.map((user: any) => ({
        id: user.id || 0,
        username: user.username || '',
        realName: user.realName || '',
        email: user.email || '',
        phoneNumber: user.phoneNumber || '',
        departmentId: user.departmentId || 0,
        position: user.position || '',
        status: user.status || 0,
        roles: [],
        createdAt: user.createdAt || '',
        updatedAt: user.updatedAt || '',
      }))
      total.value = response.data.totalElements || 0
    } else {
      users.value = []
      total.value = 0
    }
    // 记录访问日志
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: '访问用户管理页面',
    })
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    users.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await axios.get('/api/roles')
    roles.value = response.data
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取用户角色
const fetchUserRoles = async (userId: number) => {
  try {
    const response = await axios.get(`/api/users/${userId}/roles`)
    if (response.data) {
      return response.data
    }
    return []
  } catch (error: any) {
    console.error(`获取用户角色失败:`, error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
    }
    ElMessage.error(error.response?.data?.message || '获取用户角色失败')
    return []
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response = await axios.get('/api/departments')
    departments.value = response.data.map((dept: any) => ({
      ...dept,
      name: dept.fullPath || dept.name,
    }))
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 显示添加用户对话框
const showAddDialog = () => {
  isEdit.value = false
  userForm.value = {
    username: '',
    realName: '',
    phoneNumber: '',
    email: '',
    departmentId: undefined,
    position: '',
    password: '',
  }
  dialogVisible.value = true
}

// 显示编辑用户对话框
const showEditDialog = (user: User) => {
  isEdit.value = true
  currentUser.value = user
  userForm.value = {
    username: user.username,
    realName: user.realName,
    phoneNumber: user.phoneNumber,
    email: user.email,
    departmentId: user.departmentId,
    position: user.position,
    password: '',
  }
  dialogVisible.value = true
}

// 显示角色设置对话框
const showRoleDialog = async (user: User) => {
  currentUser.value = user
  roleDialogVisible.value = true
}

// 显示修改密码对话框
const showPasswordDialog = (user: User) => {
  currentUser.value = user
  passwordForm.value = {
    password: '',
    confirmPassword: '',
  }
  passwordDialogVisible.value = true
}

// 提交用户表单
const handleSubmit = async () => {
  try {
    if (isEdit.value && currentUser.value) {
      await axios.put(`/api/users/${currentUser.value.id}`, userForm.value)
      // 记录更新日志
      await axios.post('/api/logs', {
        action: 'UPDATE_USER',
        description: `更新用户：${userForm.value.username}`,
      })
      ElMessage.success('更新用户成功')
    } else {
      await axios.post('/api/users', userForm.value)
      // 记录创建日志
      await axios.post('/api/logs', {
        action: 'CREATE_USER',
        description: `创建用户：${userForm.value.username}`,
      })
      ElMessage.success('添加用户成功')
    }
    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新用户失败' : '添加用户失败')
  }
}

// 删除用户
const handleDelete = (user: User) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await axios.delete(`/api/users/${user.id}`)
      // 记录删除日志
      await axios.post('/api/logs', {
        action: 'DELETE_USER',
        description: `删除用户：${user.username}`,
      })
      ElMessage.success('删除用户成功')
      fetchUsers()
    } catch (error) {
      ElMessage.error('删除用户失败')
    }
  })
}

// 提交角色设置
const handleRoleSubmit = async () => {
  if (!currentUser.value) return
  try {
    const checkedKeys = roleTree.value.getCheckedKeys()
    await axios.put(`/api/users/${currentUser.value.id}/roles`, checkedKeys)
    // 记录角色更新日志
    await axios.post('/api/logs', {
      action: 'UPDATE_USER_ROLES',
      description: `更新用户角色：${currentUser.value.username}`,
    })
    ElMessage.success('更新角色成功')
    roleDialogVisible.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error('更新角色失败')
  }
}

// 提交密码修改
const handlePasswordSubmit = async () => {
  if (!currentUser.value) return
  if (passwordForm.value.password !== passwordForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  try {
    await axios.put(`/api/users/${currentUser.value.id}/password`, {
      password: passwordForm.value.password,
    })
    // 记录密码修改日志
    await axios.post('/api/logs', {
      action: 'UPDATE_USER_PASSWORD',
      description: `修改用户密码：${currentUser.value.username}`,
    })
    ElMessage.success('修改密码成功')
    passwordDialogVisible.value = false
  } catch (error) {
    ElMessage.error('修改密码失败')
  }
}

// 修改用户状态
const handleStatusChange = async (user: User) => {
  const action = user.status === 1 ? '禁用' : '启用'
  try {
    await axios.put(`/api/users/${user.id}/status`, {
      status: user.status === 1 ? 0 : 1,
    })
    // 记录状态更新日志
    await axios.post('/api/logs', {
      action: 'UPDATE_USER',
      description: `更新用户状态：${user.username}，状态：${user.status === 1 ? '启用' : '禁用'}`,
    })
    ElMessage.success(`${action}用户成功`)
    fetchUsers()
  } catch (error) {
    console.error('Error changing user status:', error)
    ElMessage.error(`${action}用户失败`)
    // 恢复原状态
    user.status = user.status === 1 ? 0 : 1
  }
}

// 查询
const handleQuery = () => {
  currentPage.value = 1
  fetchUsers()
}

// 重置查询
const resetQuery = () => {
  queryForm.username = ''
  queryForm.realName = ''
  queryForm.status = ''
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchUsers()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchUsers()
}

// 处理对话框打开事件
const handleDialogOpened = async () => {
  if (currentUser.value) {
    try {
      const userRoles = await fetchUserRoles(currentUser.value.id)
      if (roleTree.value) {
        roleTree.value.setCheckedKeys(userRoles.map((r: Role) => r.id))
      }
    } catch (error) {
      console.error('设置角色选中状态失败:', error)
      ElMessage.error('获取用户角色失败')
    }
  }
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: '访问用户管理页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

// 初始化
onMounted(() => {
  fetchUsers()
  fetchRoles()
  fetchDepartments()
  recordPageAccess()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.user-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.query-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.query-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 20px;
}

.query-form :deep(.el-form-item:last-child) {
  margin-right: 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.role-tag {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
